package com.boot.controller;

import com.boot.entity.*;
import com.boot.repository.*;
import com.boot.util.CSVUtils;
import com.boot.util.Constants;
import com.boot.util.StringUtil;
import com.boot.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = "*")

@RequestMapping("/stu")
public class StuInfoController {
    String namerex = "^[A-z\\u4e00-\\u9fa5]*$";
    Pattern regexName = Pattern.compile(namerex);

    public static final String REGEX_PASSWORD = "^(?![\\d]+$)(?![a-zA-Z]+$)(?![-_]+$)[\\da-zA-Z-_]{6,32}$";
    Pattern regPassword = Pattern.compile(REGEX_PASSWORD);

    String emailXX = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    Pattern regexemail = Pattern.compile(emailXX);

    public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    Pattern regexphone = Pattern.compile(REGEX_MOBILE);

    public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";
    Pattern regexCard = Pattern.compile(REGEX_ID_CARD);

    @Autowired
    private CourseInfoRepository courseInfoRepository;

    @Autowired
    private StuInfoRepository stuInfoRepository;

    @Autowired
    private SchoolRepository schoolRepository;

    @Autowired
    private MajorRepository majorRepository;


    /**
     * 导入csv 批量添加数据
     *
     * @return
     */
    @PostMapping(value = "/importCsv")
    public BaseMessage<?> upload(@RequestParam("file") MultipartFile multipartFile) {
        try {
            //上传内容不能为空
            if (multipartFile.isEmpty()) {
                return MessageHandler.createFailedVo("文件内无数据！");
            }
            File file = CSVUtils.uploadFile(multipartFile);
            List<List<String>> userRoleLists = CSVUtils.readCSV(file.getPath(), 5);

            List<String> names = new ArrayList<>();
            userRoleLists.forEach(e -> {
                StuInfo stuInfo = new StuInfo();
                stuInfo.setName(e.get(0));
                stuInfo.setStudentNumber(e.get(1));
                if (StringUtils.isNoneEmpty(e.get(2))) {
                    stuInfo.setStudentNumber(e.get(2));
                }
                if (StringUtils.isNoneEmpty(e.get(3))) {
                    stuInfo.setEmail(e.get(3));
                }
                if (StringUtils.isNoneEmpty(e.get(4))) {
                    stuInfo.setIdCard(e.get(4));
                }
                if (StringUtils.isNoneEmpty(e.get(5))) {
                    stuInfo.setSchoolId(Integer.parseInt(e.get(5)));
                }
                if (StringUtils.isNoneEmpty(e.get(6))) {
                    stuInfo.setMajorId(Integer.parseInt(e.get(6)));
                }
                stuInfo.setPassword(Constants.DEFAULT_PASSWORD);
                stuInfo.setType(Constants.STU_ROLE);
                String check = check(stuInfo);
                if (check.equals("0")) {
                    stuInfoRepository.save(stuInfo);
                } else {
                    names.add(stuInfo.getName());
                }
            });
            file.delete();
            return MessageHandler.createSuccessVo("操作成功" +( names.size() > 0 ?"沒有添加成功的學生姓名有："+ names.stream().collect(Collectors.joining(",")) : ""));
        } catch (Exception e) {
            e.printStackTrace();
            return MessageHandler.createFailedVo(e.getMessage());
        }

    }

    @RequestMapping("/stuInfo")
    public BaseMessage<?> stuInfo(String name) {
        List<StuInfo> all;
        List<StuInfoVO> allStuVO=new ArrayList<>();
        if (StringUtils.isEmpty(name)) {
            all = stuInfoRepository.findAll();
        } else {
            all = stuInfoRepository.findAllByName(name);
        }
        for(StuInfo stuInfo:all)
            allStuVO.add(stuinfoToStuInfoVO(stuInfo));
        return MessageHandler.createSuccessVo(allStuVO, "success");

    }

    @RequestMapping("/getByName")
    public BaseMessage<?> getByName(String name) {
        return MessageHandler.createSuccessVo(stuInfoRepository.findByStudentNumber(name), "success");
    }


    @RequestMapping("/saveStu")
    @Transactional
    public BaseMessage<?> saveStu(@RequestBody StuInfo stuInfo) {
        return insertStu(stuInfo);
    }


    private BaseMessage<String> insertStu(StuInfo stuInfo) {
        String check = check(stuInfo);
        if (check.startsWith("1")) {
            return MessageHandler.createFailedVo(check.substring(1));
        }
        //设置默认密码/状态/角色
        stuInfo.setPassword(Constants.DEFAULT_PASSWORD);
        stuInfo.setStatus(true);    //true是在校。
        stuInfo.setType(Constants.STU_ROLE);
        stuInfoRepository.save(stuInfo);

        Major major = majorRepository.getById(stuInfo.getMajorId());
        if (major != null) {
            major.setStuNum(major.getStuNum() + 1);
            majorRepository.save(major);
        }
        School school=schoolRepository.getById(stuInfo.getSchoolId());

        return MessageHandler.createSuccessVo("操作成功,您的初始密码为:" + Constants.DEFAULT_PASSWORD);
    }

    private String check(StuInfo stuInfo) {
        if (stuInfoRepository.existsByStudentNumber(stuInfo.getStudentNumber()) == true) {
            return "1" + "该学生已注册";
        }
        if (StringUtil.isBlank(stuInfo.getName())) {
            return "1" + "姓名不可为空";
        }
        if (StringUtil.isNotBlank(stuInfo.getName()) && !regexName.matcher(stuInfo.getName()).matches()) {
            return "1" + "姓名只能包含中英文";
        }
        if (StringUtil.isBlank(stuInfo.getStudentNumber())) {
            return "1" + "学号填写不可空";
        }
        Calendar cal = Calendar.getInstance();
        int year = (cal.get(Calendar.YEAR)) % 100;  //年份的后两位
        String regYear = stuInfo.getStudentNumber().substring(0, 2);   // 取出前两位为注册年份
        if (StringUtil.isNotBlank((stuInfo.getStudentNumber()))  //学号非空
                && !(regYear.equals(year + "") &&
                (stuInfo.getStudentNumber().length()) == Constants.STUDENTNUMBER_LENGTH)) {    //前两位为注册年份&&学号长度正确
            return "1" + "学号格式不正确";
        }
        if (StringUtil.isNotBlank(stuInfo.getEmail()) && !regexemail.matcher(stuInfo.getEmail()).matches()) {
            return "1" + "邮箱不正确";
        }
        if (StringUtil.isNotBlank(stuInfo.getIdCard()) && !regexCard.matcher(stuInfo.getIdCard()).matches()) {
            return "1" + "身份证号格式不正确";
        }
        if (StringUtil.isBlank(stuInfo.getIdCard())) {
            return "1" + "身份证不能为空";
        }
        if (StringUtil.isNotBlank(stuInfo.getPassword()) && !regPassword.matcher(stuInfo.getPassword()).matches()) {
            return "1" + "密码长度为6-32个字符；\n" +
                    "字母，数字或者特殊字符（-_）至少包含两种";
        }
        if (StringUtil.isNotBlank(stuInfo.getPhoneNumber()) && !regexphone.matcher(stuInfo.getPhoneNumber()).matches()) {
            return "1" + "手机号码格式不正确";
        }
        if (null == stuInfo.getSchoolId()) {
            return "1" + "学院id不能为空";
        }
        if (null == stuInfo.getMajorId()) {
            return "1" + "专业id不能为空";
        }
        if(false==schoolRepository.existsBySchoolId(stuInfo.getSchoolId()))
            return "1"+"该学院不存在";
        if(false==majorRepository.existsByMajorId(stuInfo.getMajorId()))
            return "1" + "该专业不存在";
        return "0";
    }

    //学生修改手机email
    @Transactional
    @RequestMapping("/updateStu")
    public BaseMessage<?> updateTea(@RequestBody ResTelAndEmail newInfo) {
        StuInfo sss = stuInfoRepository.findByStudentNumber(newInfo.getNumber());
        if (StringUtil.isNotBlank(newInfo.getEmail()) && !regexemail.matcher(newInfo.getEmail()).matches()) {
            return MessageHandler.createFailedVo("邮箱不正确");
        }
        if (StringUtil.isNotBlank(newInfo.getPhone()) && !regexphone.matcher(newInfo.getPhone()).matches()) {
            return MessageHandler.createFailedVo("手机号码格式不正确");
        }
        stuInfoRepository.save(sss);
        return MessageHandler.createSuccessVo("修改手机/email成功");
    }

    //学生修改密码
    @RequestMapping("/changePwdStu")
    public BaseMessage<?> changePwdStu(@RequestBody RestPwdVO restPwdVO) {
        if (restPwdVO.getNumber().length() != Constants.STUDENTNUMBER_LENGTH) {
            return MessageHandler.createFailedVo("学号格式不对");
        }
        if (stuInfoRepository.existsByStudentNumber(restPwdVO.getNumber()) == false) {
            return MessageHandler.createFailedVo("该学生不存在");
        }
        StuInfo uuu = stuInfoRepository.findByStudentNumber(restPwdVO.getNumber());
        if (StringUtil.isBlank(restPwdVO.getOldPassword())) {
            return MessageHandler.createFailedVo("旧密码不能为空");
        }
        if (StringUtil.isBlank(restPwdVO.getNewPassword())) {
            return MessageHandler.createFailedVo("新密码不能为空");
        }
        if (StringUtil.isNotBlank(restPwdVO.getNewPassword()) && !regPassword.matcher(restPwdVO.getNewPassword()).matches()) {
            return MessageHandler.createFailedVo("密码长度为6-32个字符；\n" +
                    "字母，数字或者特殊字符（-_）至少包含两种");
        }
        if (StringUtil.isBlank(restPwdVO.getConfirmPassword())) {
            return MessageHandler.createFailedVo("确认密码不能为空");
        }
        if (!restPwdVO.getConfirmPassword().equals(restPwdVO.getNewPassword())) {
            return MessageHandler.createFailedVo("确认密码与新密码不一致");
        }
        if (!restPwdVO.getOldPassword().equals(uuu.getPassword())) {
            return MessageHandler.createFailedVo("旧密码错误");
        }
        uuu.setPassword(restPwdVO.getNewPassword());
        stuInfoRepository.save(uuu);
        return MessageHandler.createSuccessVo("密码修改成功");
    }


    //查看可选课程
    @PostMapping("/checkMajorCourse")
    public BaseMessage<?> findCourseByMajor(@RequestParam Integer majorId) {
        Major major = majorRepository.findByMajorId(majorId);
        List<CourseInfo> courseInfoList = courseInfoRepository.findAllByMajorId(majorId);
        if (courseInfoList.get(0) == null)
            return MessageHandler.createFailedVo("没有可选课程");
        //if (courseInfoList.get(0).getStatus() == 0) {    //反正选课时间是一起开一起关的，随便选一个看看权限开了没就行
        //   return MessageHandler.createFailedVo("选课时间未到");
        //} status不用了
        else
            return MessageHandler.createSuccessVo(courseInfoList, "AvailableCourseInfo");
    }

    @Transactional
    @DeleteMapping("delStu/{stunum}")
    public BaseMessage<?> delStu(@PathVariable String stunum) {
        StuInfo stuInfo = stuInfoRepository.findByStudentNumber(stunum);
        School s = schoolRepository.findBySchoolId(stuInfo.getSchoolId());
        s.setStuNum(s.getStuNum() - 1);
        schoolRepository.save(s);

        Major m = majorRepository.findByMajorId(stuInfo.getMajorId());
        m.setStuNum(m.getStuNum() - 1);
        majorRepository.save(m);

        stuInfoRepository.delete(stuInfo);
        return MessageHandler.createSuccessVo("操作成功");
    }

    @ResponseBody
    @RequestMapping("/changeStuStatus")
    public BaseMessage<?> changeSTuStatus(@RequestParam String stuNum, Boolean status) {
        if (status == false)   //目前只考虑到在校毕业，后续若有第三状态，则将Boolean改成Integer即可
            delStu(stuNum);
        return MessageHandler.createSuccessVo("学生毕业");
    }

    @ResponseBody
    @RequestMapping("/amdinEdit")
    public BaseMessage<?> adminEdit(@RequestBody StuInfo stuInfo){
        String check = check(stuInfo);
        if (check.startsWith("1"))
            return MessageHandler.createFailedVo(check.substring(1));
        stuInfoRepository.save(stuInfo);
        return   MessageHandler.createSuccessVo("修改成功" );
    }


    public StuInfoVO stuinfoToStuInfoVO(StuInfo stuInfo){
        Major major=majorRepository.findByMajorId(stuInfo.getMajorId());
        School school=schoolRepository.findBySchoolId(stuInfo.getSchoolId());
        StuInfoVO vo=new StuInfoVO();
        vo.setName(stuInfo.getName());                  vo.setStudentNumber(stuInfo.getStudentNumber());
        vo.setPhoneNumber(stuInfo.getPhoneNumber());    vo.setEmail(stuInfo.getEmail());
        vo.setIdCard(stuInfo.getIdCard());              vo.setPassword(stuInfo.getPassword());
        vo.setMajorName(major.getMajorName());          vo.setSchoolName(school.getSchoolName());
        vo.setStatus(stuInfo.getStatus());              vo.setChangePassword(stuInfo.getChangePassword());
        vo.setType(stuInfo.getType());
        return vo;
    }

}



